package com.weixing.mall.provider.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.annotation.SysLog;
import com.weixing.mall.core.enums.OperateEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AgentAuth;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.support.auth.SysInfo;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.model.domain.AgentRenew;
import com.weixing.mall.provider.model.dto.renew.AgentRenewDto;
import com.weixing.mall.provider.model.dto.renew.AgentRenewEditDto;
import com.weixing.mall.provider.model.enums.AgentPayChannelEnum;
import com.weixing.mall.provider.model.enums.AgentPayTypeEnum;
import com.weixing.mall.provider.model.query.AgencyFeeQuery;
import com.weixing.mall.provider.model.query.AgencyRecordQuery;
import com.weixing.mall.provider.model.vo.AgencyFeeVo;
import com.weixing.mall.provider.model.vo.AgentRenewTableVo;
import com.weixing.mall.provider.model.vo.AgentRenewVo;
import com.weixing.mall.provider.model.vo.renew.AgencyRecordExcelData;
import com.weixing.mall.provider.model.vo.renew.AgentRenewEditVo;
import com.weixing.mall.provider.model.vo.renew.RenewStats;
import com.weixing.mall.provider.service.IAgentLogService;
import com.weixing.mall.provider.service.IAgentRenewService;
import com.weixing.mall.provider.service.IAgentService;
import com.weixing.mall.provider.support.excel.AgencyExcelDownData;
import com.weixing.mall.provider.support.excel.AgentRenewExcelData;
import com.weixing.mall.provider.support.excel.AgentRenewImportDataListener;
import com.weixing.mall.provider.util.AgentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * 代理商缴费
 *
 * @author siashan
 * @since v1.0
 **/
@Validated
@RestController
@RequestMapping("agent/renew")
public class AgentRenewController extends BaseController {

    @Autowired
    private IAgentRenewService agentRenewService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentLogService agentLogService;

    /**
     * 代理缴费列表
     *
     * TODO V2版本上线后可删除
     * @param auth
     * @param agentRenewQuery  缴费查询
     * @return 缴费列表
     */
    @GetMapping("")
    @Deprecated
    public Result list(@SysInfo SysAuth auth, AgencyFeeQuery agentRenewQuery) {
        IPage<AgencyFeeVo> pageInfo = agentRenewService.selectAgencyFeeListOfPage(initMpPage(), agentRenewQuery, auth);
        return ResultUtil.success(pageInfo);
    }
    /**
     * 代理缴费列表-v2
     *
     * @param agentRenewQuery  缴费查询
     * @return 缴费列表
     */
    @GetMapping("renewList")
    public Result<IPage<AgencyFeeVo>> renewList(AgencyFeeQuery agentRenewQuery) {
        IPage<AgencyFeeVo> pageInfo = agentRenewService.selectRenewList(initMpPage(), agentRenewQuery);
        return ResultUtil.success(pageInfo);
    }


    /**
     * 代理缴费记录--(代理缴费详情菜单)-v2
     *
     * @param query  缴费查询
     * @return 缴费列表
     */
    @GetMapping("record/list")
    public Result<AgentRenewTableVo> recordList(AgencyRecordQuery query) {
        IPage<AgentRenewVo> pageInfo = agentRenewService.selectRenewRecordList(initMpPage(), query);
        AgentRenewTableVo tableVo = new AgentRenewTableVo();
        tableVo.setPageData(pageInfo);
        RenewStats stats = agentRenewService.renewStats(query);
        tableVo.setStats(stats);
        return ResultUtil.success(tableVo);
    }

    /**
     * 代理缴费记录导出--v2
     *
     * @param query     查询条件
     * @param response  HttpServletResponse
     */
    @SysLog(type = OperateEnum.D,desp = "代理缴费记录导出")
    @GetMapping("record/import")
    public void recordImport(AgencyRecordQuery query, HttpServletResponse response) {
        Page page = initMpPage();
        page.setSize(-1);
        IPage<AgentRenewVo> pageInfo = agentRenewService.selectRenewRecordList(page, query);
        List<AgentRenewVo> records = pageInfo.getRecords();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("代理缴费记录", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AgencyRecordExcelData.class).sheet("sheet1").doWrite(AgentUtil.wapperAgencyRecordExcelData(records));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 代理缴费记录详情--v2
     *
     * @param id    缴费记录id
     * @return 缴费详情
     */
    @GetMapping("detail/{id}")
    public Result<AgentRenewEditVo> detail(@PathVariable long id) {
        AgentRenew agentRenew = agentRenewService.getById(id);
        Agent agent = agentService.getById(agentRenew.getAgentId());
        AgentRenewEditVo vo = AgentUtil.wrapAgentRenewEditVo(agentRenew,agent);
        return ResultUtil.success(vo);
    }

    /**
     * 代理缴费记录修改--v2
     *
     * @param dto   缴费记录修改dto
     * @return 修改结果
     */
    @PostMapping("record/edit")
    public Result editRecord(@Validated  AgentRenewEditDto dto) {
        agentRenewService.editRecord(dto);
        return ResultUtil.success();
    }


    /**
     * 代理缴费记录 详情
     * @param agentId 代理id
     * @return 缴费记录
     */
    @GetMapping("list/{agentId}")
    public Result<IPage<AgentRenewVo>> getAgentRenew(@PathVariable Long agentId) {
        IPage<AgentRenewVo> agentRenewVo = agentRenewService.agentRenewList(initMpPage(), agentId);
        return ResultUtil.success(agentRenewVo);
    }


    /**
     * 代理商端--代理缴费列表
     *
     * @param query  查询条件
     * @return 缴费记录
     */
    @GetMapping("/agent")
    public Result listForAgent( AgencyFeeQuery query) {
        AgentAuth auth = AuthUtil.getAgentExt();
        query.setAgentId(auth.getAid());
        IPage<AgentRenewVo> agentRenewVo = agentRenewService.agentRenewList(initMpPage(), auth.getAid());
        return ResultUtil.success(agentRenewVo);
    }


    /**
     * 更改代理代理费
     *
     * @param agentId   代理商id
     * @param agencyFeeYear     按年缴费金额
     * @param agencyFeeMonth    按月缴费金额
     * @return 变更结果
     */
    @PostMapping("chgAgentFee/{agentId}")
    @SysLog(type = OperateEnum.S, desp = "更改代理商代理费")
    public Result chgAgentFee(@PathVariable Long agentId, BigDecimal agencyFeeYear, BigDecimal agencyFeeMonth) {
        Agent agent = agentService.getById(agentId);
        agent.setAgencyFeeYear(agencyFeeYear);
        agent.setAgencyFeeMonth(agencyFeeMonth);
        agentService.updateById(agent);
        return ResultUtil.success();
    }

    /**
     * 查看缴费记录详情
     *
     * @param id    缴费记录id
     * @return 缴费详情
     */
    @GetMapping("{id}")
    public Result<AgentRenewEditVo> get(@PathVariable long id) {
        AgentRenew agentRenew = agentRenewService.getById(id);
        Agent agent = agentService.getById(agentRenew.getAgentId());
        AgentRenewEditVo vo = new AgentRenewEditVo();
        vo.setId(agentRenew.getId());
        vo.setAgentId(agent.getId());
        vo.setAgentSn(agent.getAgentSn());
        vo.setAgentName(agent.getAgentName());
        vo.setAgentLevel(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()));
        vo.setAmount(agentRenew.getAmount());
        vo.setCreatedTime(agentRenew.getCreatedTime());
        vo.setCustomerName(agent.getCustomerName());
        vo.setEffectEnd(agentRenew.getEffectEnd());
        vo.setEffectStart(agentRenew.getEffectStart());
        vo.setMobile(agent.getMobile());
        vo.setPayChannel(EnumUtil.getIEnum(AgentPayChannelEnum.class, agentRenew.getPayChannel()));
        vo.setPayType(EnumUtil.getIEnum(AgentPayTypeEnum.class, agentRenew.getPayType()));
        return ResultUtil.success(vo);
    }

    /**
     * 保存代理缴费记录
     *
     * @param agentRenewDto 参数
     * @return 结果
     */
    @PostMapping("save")
    @NoRepeatSubmit
    @SysLog(type = OperateEnum.S, desp = "保存代理缴费记录")
    public Result save(@Validated AgentRenewDto agentRenewDto) {
        SysAuth auth = AuthUtil.getSysExt();
        return ResultUtil.success(agentRenewService.save(agentRenewDto, auth));
    }

    /**
     * 代理缴费列表 导出
     * @param agentRenewQuery 查询条件
     * @param response HttpServletResponse
     */
    @SysLog(type = OperateEnum.D,desp = "代理缴费列表导出")
    @GetMapping("excel")
    public void excel(AgencyFeeQuery agentRenewQuery, HttpServletResponse response) {
        List<AgencyFeeVo> voList = agentRenewService.selectAgencyFeeList(agentRenewQuery);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("代理缴费列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AgencyExcelDownData.class).sheet("sheet1").doWrite(AgentUtil.wapperAgencyExcelData(voList));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 代理缴费导入模板下载
     * @param response
     */
    @GetMapping("renewTemplate")
    public void excel(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("代理缴费导入模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AgentRenewExcelData.class).sheet("sheet1").doWrite(Lists.newArrayList());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 代理商批量缴费导入
     * @param file 导入文件
     * @return 结果
     */
    @PostMapping(value = "agentRenewImport")
    public Result agentRenewImport(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), AgentRenewExcelData.class, new AgentRenewImportDataListener(agentService, agentRenewService, agentLogService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("success");
    }
}
